#include <stdio.h>
#include <sys/timeb.h>
#include <thread>
#include <atomic>
#include "threadpool.h"

bool exit_ = false;

void *
task(void *data, int id)
{
    srand(time(NULL) + id);
    /* srand(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count()); */
    int count = rand() % 1000;

    /* printf("count %d\n", count); */
    std::this_thread::sleep_for(std::chrono::milliseconds(count));

    return NULL;
}

void
launch_rand(void *data)
{
    ThreadPool *tpool = (ThreadPool *)data;

    while (!exit_)
    {
        /* srand(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count()); */
        srand(time(NULL));
        int N = rand() % 10 + 1;

        for (int i = 0; i < N; ++i)
        {
            while (tpool->launch(task, NULL, i) < 0)
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

ThreadPool *tpool = NULL;
int main(int argc, char *argv[])
{
    tpool = new ThreadPool();

    std::thread t(launch_rand, tpool);

    getchar();
    exit_ = true;
    t.join();

    if (tpool)
    {
        delete tpool;
    }

    getchar();

    return 0;
}
